#!/bin/sh
#
# choose -- Choose a lab
#
# Copyright (C) 2016-2021 Wu Zhangjin <falcon@ruma.tech>
#

NEW_LAB=$1

TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd)"

[ $# -gt 0 ] && shift
. "$TOP_DIR"/tools/docker/config >/dev/null
OLD_LAB=$CURRENT

[ -z "$PULL" ] && PULL=0

[ -z "$SUBMODULE" ] && SUBMODULE=0

# main branch
DEF_BRANCH=master
get_var BRANCH

# Fix up windows support
config_casesensitive ()
{
    # should enable case sensitive for ntfs filesystem
    if [ "x$HOST_OS" = "xWindows" ]; then
      echo "LOG: Please enable case sensitive as administrator: fsutil file SetCaseSensitiveInfo '$(cd "$TOP_DIR" && pwd -W | sed -e 's%/%\\%g')' enable"
    fi
}

config_git ()
{
    git config --global core.safecrlf true
    if [ "x$HOST_OS" = "xWindows" ]; then
        git config --global core.autocrlf false
    fi
}

download_submodule ()
{
    LAB_CURRENT_DIR="$LAB_DIR"/$CURRENT

    if [ -n "$CURRENT" ]; then
      LABS=$CURRENT
    else
      LABS=`get_labs`
    fi

    for lab in $LABS; do
      LAB_CURRENT_DIR="$LAB_DIR"/$lab
      [ $SUBMODULE -eq 1 ] && \
	RECURSIVE=" --recursive " && \
	PULL_RECURSIVE=" --recurse-submodules=yes "

      [ ! -f "$LAB_CURRENT_DIR"/.git ] \
        && git submodule update --init --remote $RECURSIVE "$LAB_CURRENT_DIR" \
        && cd "$LAB_CURRENT_DIR" && git checkout $BRANCH

      [ $PULL -eq 1 ] && info_print "Pull repository: $lab" \
        && git pull -v && git submodule sync && git pull $PULL_RECURSIVE -v

      [ $SUBMODULE -eq 1 ] && info_print "Pull submodules of $lab" \
	&& git submodule update --init --remote $RECURSIVE .

      # Convert absolute path to relative path for gitdir in .git of submodules
      [ $SUBMODULE -eq 1 ] && \
        git submodule foreach --recursive '[ -f .git ] && gitdir=$(cut -d" " -f2 .git) && (echo $gitdir | grep -q ^/) && dir=$(echo $gitdir | sed -e 's%$TOP_DIR/%%') && relpath=$(echo $PWD | sed -e 's%$TOP_DIR%%g' | tr -c -d '/' | sed -e 's%/%../%g') && echo "gitdir: $(echo $relpath)$dir" > .git || :'

      info_print "Source code downloaded to $LAB_CURRENT_DIR"
    done
}

if [ -n "$NEW_LAB" ]; then
    CURRENT=$NEW_LAB

    . "$TOP_DIR"/tools/docker/config >/dev/null

    set_var CURRENT

    [ -n "$OLD_LAB" -a "$OLD_LAB" != "$CURRENT" ] && info_print "Switch from $OLD_LAB to $CURRENT"
    download_submodule && exit 0
fi

info_print "Available Labs:"
echo
get_labs | tr ' ' '\n' | nl -v 1
echo

read -p 'INFO: Choose the lab number: ' number

[ -z "$number" ] && echo "ERR: No valid number specified." && exit 1

CURRENT=`get_labs | tr ' ' '\n' | head -$number | tail -1`

echo
get_labs | tr ' ' '\n' | nl -v 1 | grep " $number"
echo

set_var CURRENT

echo
info_print "Download the lab..."
echo

# Hacking for windows support, disable autocrlf switch
config_git
config_casesensitive

# Clone the submodule
download_submodule
